package cn.zzp.basic.util;

import cn.zzp.basic.jwt.LoginData;
import cn.zzp.basic.jwt.Payload;
import cn.zzp.basic.jwt.RsaUtils;
import cn.zzp.user.domain.LoginInfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

import static cn.zzp.basic.jwt.JwtUtils.getInfoFromToken;

/**
 * @ClassName LoginContext
 * @Description 获取登录人信息
 * @Author 祝志鹏
 * @Date 2022/8/9 10:51
 */
public class LoginContext {

    public static LoginInfo getLoginInfo(HttpServletRequest request) {
        try {
            // 1. 取出token,前端将token存入请求头内，直接调方法取
            String jwtToken = request.getHeader("token");
            if (jwtToken != null) {
                // 解密
                // 获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                Payload<LoginData> payload = getInfoFromToken(jwtToken, publicKey, LoginData.class);

                if (payload != null) {//登录成功，而且没有过期
                    //5.如获取登录信息对象
                    LoginInfo loginInfo = payload.getLoginData().getLoginInfo();
                    return  loginInfo;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
